import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import axios from 'axios';
import qs from 'qs';
import JoinForm from './JoinForm';
import { updateInput, clearAllFields } from '@/actions/updateInputFields';
import './style.scss';

class Home extends Component {
  handleChange = (num, val) => {
    let { fields } = this.props.inputFields;
    fields[num] = val;
    this.props.updateInput(fields);
  };

  handleSubmit = e => {
    e.preventDefault();
    const { validateFields } = this.props.form;
    const { fields } = this.props.inputFields;
    console.log(fields);
    validateFields((error, values) => {
      if (!error) {
        console.log(values);
      } else {
        for (let key in error) {
          Toast.fail(error[key].errors[0].message, 1);
          break;
        }
      }
    });
    this.props.history.push({ pathname: '/result', query: { key: 1 } });
  };

  createJoinInfo = data => {
    if (!data || typeof data !== 'object') return;
    const { baseUrl } = this.props;
    const params = qs.stringify(data);

    axios
      .post(`${baseUrl}/`, params)
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        try {
          Toast.fail(err.response.data.message);
        } catch (e) {
          console.log(e);
        }
      });
  };

  render() {
    return (
      <div>
        <h2 className="page__title">青春在线纳新报名</h2>
        <JoinForm
          form={this.props.form}
          inputFields={this.props.inputFields}
          handleChange={this.handleChange}
        />
        <Button type="primary" className="btn-area" onClick={this.handleSubmit}>
          提交
        </Button>
        <div className="page__copyright">© 2018 青春在线</div>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  baseUrl: state.baseUrl,
  inputFields: state.inputFields,
});

const mapDispatchToProps = dispatch => ({
  updateInput: bindActionCreators(updateInput, dispatch),
  clearAllFields: bindActionCreators(clearAllFields, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(createForm()(Home));
